import { useEffect, useState } from 'react';
import { useModel } from 'umi';
import FilterDrawer from './components/FilterDrawer';
import { Button, Col, Image, Modal, Row, Spin, Tooltip, message } from 'antd';
import { LeftOutlined, QuestionCircleOutlined, RightOutlined } from '@ant-design/icons';
import CurrDataView from './components/CurrDataView';
import {
  ProForm,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import {
  AbnormalOrderStatus,
  AbnormalOrderTypeEnum,
  PlateColorOptions,
  SENSOR_STATUS_MAP,
} from '../abnormal-order';
import { PlateColorEnum } from '@/pages/Parking/Records/types.d';
import moment from 'moment';
import {
  getConflictOrder,
  getCurrRecord,
  getLastAbnormalRecord,
  getNeiborhoodReocrd,
  getPatrolImgs,
  precheckPlateNumber,
  reviseAbnormalOrder,
} from '../service';
import { handleInOutType, handleTime, isHttps } from '@/utils/utils';
import { getHistoryParkingRecord } from '../service';
import FixedView from './components/FixedView';
import StatusNotMatchView from './components/StatusNotMatchView';
import LicenseChangedView from './components/LicenseChangedView';
import ConflictView from './components/ConflictView';

interface ReviseProps {
  data?: AbnormalOrderTableItem;
  canSearchUser?: boolean;
  searchCondition: {
    ownerId?: string;
    type?: AbnormalOrderType;
    status?: AbnormalOrderStatusType;
    parkingLotId?: string;
  };
}

const ReviseView = (props: ReviseProps) => {
  const { data, canSearchUser, searchCondition } = props;
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;

  // 记录上一条id
  const [lastAboId, setlastAboId] = useState<string>(data?._id || '');

  // 预检
  const [precheckModalVisible, setPrecheckModalVisible] = useState(false);
  const [precheckResult, setPrecheckResult] = useState<PrecheckResultType | null>(null);
  const [reviseData, setReviseData] = useState<AboCorrectParams | null>(null);

  const [currentData, setCurrentData] = useState<AbnormalOrderTableItem | undefined>(data);
  // 图片
  const [composeImageUrl, setComposeImageUrl] = useState<string>('');
  // 停车记录数组
  const [parkRecords, setParkRecords] = useState<SpotParkingRecordItem[]>([]);
  // 当前停车记录
  const [currParkRecord, setCurrParkRecord] = useState<ParkingRecordParams | null>(null);
  // 冲突订单
  const [conflictOrder, setConflictOrder] = useState<ConflictOrderParams | null>(null);

  const [loading, setLoading] = useState<boolean>(false);

  const [continuous, setContinuous] = useState<string>('close');

  // 过滤条件
  const [ownerIds, setOwnerIds] = useState<string[]>(
    searchCondition.ownerId ? [searchCondition.ownerId] : [],
  );
  const [parkingLotIds, setParkingLotIds] = useState<string[]>(
    searchCondition.parkingLotId ? [searchCondition.parkingLotId] : [],
  );
  const [types, setTypes] = useState<AbnormalOrderType[]>(
    searchCondition.type ? [searchCondition.type] : [],
  );
  const [status, setStatus] = useState<AbnormalOrderStatusType[]>(
    searchCondition.status ? [searchCondition.status] : [],
  );

  // 丢弃
  const [cancelAbo, setCancelAbo] = useState<boolean>(false);

  const [fixForm] = ProForm.useForm();

  const waitingFix = currentData?.status == AbnormalOrderStatus.WAITING;
  const clearData = () => {
    setCurrentData(undefined);
    setComposeImageUrl('');
    setParkRecords([]);
  };

  // 上一条记录 / 下一条记录
  const getData = async (flag: AboQueryFlag, filter = false) => {
    console.log(currentData);
    let ifLast = !!currentData;
    console.log('ifLast', ifLast);
    setLoading(true);
    clearData();
    const reqData: QueryNeiborRecordParam = {
      id: currentData?._id || '',
      ownerId: ownerIds,
      parkingLotId: parkingLotIds,
      type: types,
      status: status,
      filter,
      flag,
    };
    const { success, data } =
      !ifLast && flag == 'prev'
        ? await getLastAbnormalRecord(lastAboId)
        : await getNeiborhoodReocrd(reqData);

    setLoading(false);
    if (!success) {
      message.warn({ content: '获取数据失败', key: 'revise_view' });
      return;
    }
    if (!data) {
      message.warn({ content: '没有更多数据了！', key: 'revise_view' });
      return;
    }
    console.log('data ====>', data);
    setlastAboId(data._id);
    setCurrentData(data);
    fixForm?.resetFields();
  };

  // 完成审核
  const preSubmit = async (rd: AboCorrectParams) => {
    if (!currentData || !rd) return;
    setReviseData(rd);
    if (!rd.cancelAbo && rd.plateNumber) {
      const precheck = await precheckPlateNumber({
        plateNumber: rd.plateNumber,
        owenrId: currentData?.ownerId,
        parkingLotId: currentData?.parkingLotId,
        spotId: rd.spotId,
      });
      if (!precheck?.success) {
        if (!precheck?.data) {
          message.error({ content: precheck?.message, key: 'revise_view' });
          return;
        }
        setPrecheckResult(precheck.data);
        setPrecheckModalVisible(true);
        return;
      }
    }
    await submitRevise(rd);
  };
  const submitRevise = async (rd: AboCorrectParams) => {
    if (
      currentData?.type != AbnormalOrderTypeEnum.LICENSE_CHANGED &&
      currentData?.type != AbnormalOrderTypeEnum.LICENSE_SIMILAR &&
      currentData?.type != AbnormalOrderTypeEnum.UNKNOWN_LICENSE
    ) {
      rd.changeCar = false;
    }
    const res = await reviseAbnormalOrder(rd);
    setReviseData(null);
    if (!res.success) {
      message.error({
        content: res.message,
        key: 'revise_view',
      });

      return;
    }
    message.success({
      content: '审核成功',
      key: 'revise_view',
    });
    if (res.data) setCurrentData(res.data);
    if (continuous == 'next') getData('next', true);
    if (continuous == 'prev') getData('prev', true);
    return true;
  };

  const defaultAboView = (title: string = '巡检图片') => {
    return (
      <>
        {composeImageUrl && (
          <div style={{ textAlign: 'center', color: 'red' }}>
            <strong>{title}</strong>
            <div
              style={{
                background: 'black',
                border: '1px solid #FFF',
                margin: '0 auto',
              }}
            >
              <Image
                alt="巡检图片"
                style={{ maxHeight: 440 }}
                src={isHttps ? composeImageUrl : composeImageUrl.replace('http://', 'https://')}
              />
            </div>
          </div>
        )}
      </>
    );
  };

  // 修正操作表单
  const renderNotFixedView = () => {
    return (
      <div style={{ marginTop: 15 }}>
        <ProForm<AboFixFormParams>
          form={fixForm}
          layout="horizontal"
          initialValues={{
            deviceSn: currentData?.sensorData?.deviceSn || '无数据',
            status: SENSOR_STATUS_MAP.get(currentData?.sensorData?.status) || '无数据',
            changeTime: currentData?.sensorData?.changeTime
              ? moment(currentData.sensorData.changeTime).format('YYYY-MM-DD HH:mm:ss')
              : '无数据',
            plateNumber: currentData?.plateNumber,
            plateColor: currentData?.plateColor || PlateColorEnum.unknown,
            spotId: currentData?.spotId || '',
            remark: '',
            isSpotEmpty: currentData?.type == AbnormalOrderTypeEnum.SENSOR_FREE_PATROL_OCCUPY,
            changeCar: true,
          }}
          submitter={false}
          onFinish={async (formData) => {
            console.log('first submit', formData, currentData);
            if (!currentData) return;
            return await preSubmit({
              id: currentData._id,
              plateNumber: formData.plateNumber,
              plateColor: formData.plateColor,
              remark: formData.remark,
              spotId: formData.spotId,
              cancelAbo,
              changeCar: formData.changeCar,
            });
          }}
        >
          <ProFormText label="地磁编号" name="deviceSn" disabled />
          <ProFormText label="地磁状态" name="status" disabled />
          <ProFormText label="地磁时间" name="changeTime" disabled />
          <ProFormText
            disabled={cancelAbo}
            label="泊位编号"
            name="spotId"
            placeholder="请输入修正后的泊位编号"
          />
          <ProFormText
            disabled={cancelAbo}
            label="车牌号码"
            name="plateNumber"
            placeholder="请输入修正后的车牌号码"
          />
          <ProFormSelect
            label="车牌颜色"
            name="plateColor"
            disabled={cancelAbo}
            placeholder="请选择修正后的车牌颜色"
            options={PlateColorOptions}
          />
          {(currentData?.type == AbnormalOrderTypeEnum.LICENSE_CHANGED ||
            currentData?.type == AbnormalOrderTypeEnum.LICENSE_SIMILAR ||
            currentData?.type == AbnormalOrderTypeEnum.UNKNOWN_LICENSE) && (
            <ProFormRadio.Group
              name="changeCar"
              label="车辆变化"
              initialValue={true}
              options={[
                { label: ' < 是 > ', value: true },
                { label: ' < 否 > ', value: false },
              ]}
              fieldProps={{
                optionType: 'button',
                buttonStyle: 'solid',
                size: 'middle',
              }}
            />
          )}
          <ProFormTextArea
            label="审核备注"
            name="remark"
            placeholder={'请输入本次审核的备注事项'}
          />
          <div style={{ marginBottom: 18, display: 'flex' }}>
            <Button
              disabled={cancelAbo}
              onClick={() => {
                fixForm.setFieldsValue({
                  plateNumber: '未知车牌',
                  plateColor: PlateColorEnum.unknown,
                  isSpotEmpty: false,
                });
              }}
            >
              未知车牌
            </Button>
            <Button
              disabled={cancelAbo}
              style={{ marginLeft: 10 }}
              onClick={() => {
                fixForm.setFieldsValue({
                  plateNumber: '',
                  plateColor: PlateColorEnum.unknown,
                  isSpotEmpty: true,
                });
              }}
            >
              泊位无车
            </Button>
            <Button
              disabled={cancelAbo}
              onClick={() => {
                fixForm.setFieldsValue({
                  plateNumber: '无',
                  plateColor: PlateColorEnum.unknown,
                  isSpotEmpty: false,
                });
              }}
              style={{ marginLeft: 10 }}
            >
              无牌车
            </Button>
            <Button
              type={cancelAbo ? 'primary' : 'default'}
              onClick={() => {
                setCancelAbo(!cancelAbo);
              }}
              style={{ marginLeft: 10 }}
            >
              作废异常
            </Button>
          </div>
          <div style={{ marginBottom: 10 }}>
            <Button
              type="primary"
              danger
              size="large"
              style={{ width: '100%' }}
              onClick={() => {
                console.log('点击了提交按钮');
                fixForm.submit();
              }}
            >
              {cancelAbo ? '点击作废当前记录' : '点击完成审核'}
            </Button>
          </div>
          <ProFormRadio.Group
            name="continuous"
            label="审核后自动跳转"
            tooltip="自动跳转只会筛选未审核的数据"
            options={[
              { label: '上一条记录', value: 'prev' },
              { label: '下一条记录', value: 'next' },
              { label: '关闭', value: 'close' },
            ]}
            fieldProps={{
              value: continuous,
              onChange: (e) => setContinuous(e.target.value),
            }}
          />
        </ProForm>
      </div>
    );
  };

  // 根据审核类型不同渲染不同界面
  const renderWhichView = (type?: AbnormalOrderType) => {
    if (!type) return '暂无数据';
    if (type <= AbnormalOrderTypeEnum.UNKNOWN_LICENSE) {
      // 本次巡检的图片
      return (
        <StatusNotMatchView
          ifPatrol={!currentData?.sensorData}
          type={type}
          composeImageUrl={composeImageUrl}
          parkRecords={parkRecords}
        />
      );
    }
    if (type <= AbnormalOrderTypeEnum.LICENSE_CHANGED) {
      return (
        currParkRecord &&
        currentData && (
          <LicenseChangedView
            composeImageUrl={composeImageUrl}
            currParkRecord={currParkRecord}
            currentData={currentData}
          />
        )
      );
    }
    if (type == AbnormalOrderTypeEnum.LICENSE_CONFLICT) {
      return (
        conflictOrder &&
        currentData && (
          <ConflictView
            composeImageUrl={composeImageUrl}
            conflictOrder={conflictOrder}
            currentData={currentData}
          />
        )
      );
    }
    return defaultAboView();
  };

  useEffect(() => {
    if (!currentData?.taskId) return;
    getPatrolImgs(currentData.taskId).then((res) => {
      if (!res.success) {
        message.warn({ content: res.message, key: 'revise_view' });
        return;
      }
      if (res.data) {
        const { composeImageUrl } = res.data;

        if (composeImageUrl) {
          setComposeImageUrl(composeImageUrl);
        }
      }
    });
  }, [currentData?.taskId]);
  useEffect(() => {
    if (!currentData?.spotId || currentData?.type > AbnormalOrderTypeEnum.UNKNOWN_LICENSE) return;
    // 获取停车数据数组
    getHistoryParkingRecord({
      spotId: currentData.spotId,
      parkingLotId: currentData.parkingLotId,
      ownerId: currentData.ownerId,
      patrolTime: currentData.patrolTime,
    }).then((res) => {
      if (!res.success) {
        message.warn({ content: res.message, key: 'revise_view' });
        return;
      }
      if (res.data) {
        setParkRecords(res.data);
      }
    });
  }, [currentData?.spotId]);
  useEffect(() => {
    if (!currentData?.parkingRecordId) return;
    if (
      currentData?.type != AbnormalOrderTypeEnum.LICENSE_CHANGED &&
      currentData?.type != AbnormalOrderTypeEnum.LICENSE_SIMILAR
    )
      return;
    // 获取停车记录
    getCurrRecord(currentData.parkingRecordId).then((res) => {
      if (!res.success) {
        message.warn({ content: res.message, key: 'revise_view' });
        return;
      }
      if (res.data) {
        setCurrParkRecord(res.data);
      }
    });
  }, [currentData?.parkingRecordId]);
  useEffect(() => {
    if (!currentData?.relatedOrderNo) return;
    if (currentData.type != AbnormalOrderTypeEnum.LICENSE_CONFLICT) return;
    // 获取冲突订单
    getConflictOrder(currentData.relatedOrderNo).then((res) => {
      if (!res.success) {
        message.warn({ content: res.message, key: 'revise_view' });
        return;
      }
      if (res.data) {
        setConflictOrder(res.data);
      }
    });
  }, [currentData?.relatedOrderNo]);

  return (
    <div style={{ marginTop: 0 }}>
      <div
        style={{
          height: 48,
          width: '100vw',
          backgroundColor: '#eee',
          display: 'flex',
          boxShadow: '0px 0px 5px 0px rgba(20,20,20,0.5)',
        }}
      >
        <div
          style={{
            marginLeft: 10,
            height: 48,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
          }}
        >
          <img src="/logo.svg" width={42} height={42} />
        </div>
        <div
          style={{
            width: 300,
            marginLeft: 15,
            height: 48,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
          }}
        >
          <span style={{ color: '#5993d0', fontSize: 20, fontWeight: 'bold' }}>一九智慧停车</span>
        </div>
        <div
          style={{
            marginLeft: 'auto',
            display: 'flex',
            alignItems: 'center',
            color: 'black',
            marginRight: 20,
          }}
        >
          <span>
            <FilterDrawer
              onOk={(values) => {
                if (!values) return;
                setOwnerIds(values.ownerId || []);
                setParkingLotIds(values.parkingLotId || []);
                setTypes(values.type || []);
                setStatus(values.status || []);
              }}
              selectVal={{
                ownerId: ownerIds,
                parkingLotId: parkingLotIds,
                type: types,
                status: status,
              }}
              canSearchUser={canSearchUser}
            />
          </span>
          <img src="/user.svg" width={25} height={25} />
          <span style={{ marginLeft: 5 }}>{currUser?.userName}</span>
        </div>
      </div>
      <Spin tip="加载中..." spinning={loading}>
        <div style={{ marginTop: 20 }}>
          <Row gutter={8}>
            <Col span={16}>
              <div style={{ width: '98%', marginLeft: '1%' }}>
                {renderWhichView(currentData?.type)}
              </div>
            </Col>
            <Col span={8}>
              <div style={{ width: '95%' }}>
                <div>
                  <div style={{ width: '50%', display: 'inline-block', textAlign: 'left' }}>
                    <Button
                      type="primary"
                      size="large"
                      onClick={() => {
                        console.log('执行上一条记录');
                        getData('prev', false);
                      }}
                    >
                      <LeftOutlined />
                      上一条记录
                    </Button>
                  </div>
                  <div style={{ width: '50%', display: 'inline-block', textAlign: 'right' }}>
                    <Button type="primary" size="large" onClick={() => getData('next', false)}>
                      下一条记录
                      <RightOutlined />
                    </Button>
                  </div>
                </div>

                {currentData && <CurrDataView currData={currentData} />}

                {waitingFix && renderNotFixedView()}

                {currentData?.status == AbnormalOrderStatus.HANDLED && (
                  <FixedView currData={currentData} />
                )}
              </div>
            </Col>
          </Row>
        </div>
      </Spin>
      {precheckModalVisible && precheckResult && (
        <Modal
          title="车牌号校验失败"
          open={precheckModalVisible}
          onCancel={() => {
            setPrecheckModalVisible(false);
            setPrecheckResult(null);
            setReviseData(null);
          }}
          footer={[
            <Button
              key="back"
              onClick={() => {
                setPrecheckModalVisible(false);
                setPrecheckResult(null);
                setReviseData(null);
              }}
            >
              返回重填
            </Button>,
            <Button
              key="cancel"
              danger
              onClick={async () => {
                if (!reviseData) {
                  message.error({ content: '未获取到修正数据', key: 'revise_view' });
                  setPrecheckModalVisible(false);
                  setPrecheckResult(null);
                  return;
                }
                reviseData.cancelAbo = true;
                await submitRevise(reviseData);
                setPrecheckModalVisible(false);
                setPrecheckResult(null);
              }}
            >
              作废当前记录
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={async () => {
                if (!reviseData) {
                  message.error({ content: '未获取到修正数据', key: 'revise_view' });
                  setPrecheckModalVisible(false);
                  setPrecheckResult(null);
                  return;
                }
                reviseData.outOrder = precheckResult.orderNo;
                await submitRevise(reviseData);
                setPrecheckModalVisible(false);
                setPrecheckResult(null);
              }}
            >
              继续提交{' '}
              <Tooltip title={`此操作将驶出订单${precheckResult.orderNo}`}>
                <QuestionCircleOutlined />
              </Tooltip>
            </Button>,
          ]}
        >
          <div>
            车牌号码「{precheckResult.plateNumber}」已在路段 <b>{precheckResult.parkingLotName}</b>{' '}
            的 <b>{precheckResult.spotId}泊位</b> 停放
          </div>
          <div>驶入时间：{handleTime(precheckResult.inTime)}</div>
          <div>驶入方式：{handleInOutType(precheckResult.inType)}</div>
          <div>订单编号：{precheckResult.orderNo}</div>
        </Modal>
      )}
    </div>
  );
};

export default ReviseView;
